﻿using Newtonsoft.Json;
using SqlSugar;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WCS.Entity;
using WCS.Helpers;
using WCS.Helpers.ExportExcel;
using WCS.Utils;
using WCS.WebRequest;
using static System.Collections.Specialized.BitVector32;

namespace WCS.Controls
{
    public partial class CastingMaterial : UIPage
    {
        public CastingMaterial()
        {
            InitializeComponent();
        }
        public static string connStrings = System.Configuration.ConfigurationManager.AppSettings["SQLConn"].ToString();

        Dictionary<string, string> _station = new Dictionary<string, string>()
        {
            { "D1","3001"},
            { "D2","3002"},
            { "D3","3003"},
            { "D4","3004"},
            { "D5","3005"},
            { "C1","3006"},
            { "C2","3007"},
            { "C3","3008"},
            { "C4","3009"},
            { "C5","3010"}
        };

        /// <summary>
        /// 窗体加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SortingTask_Load(object sender, EventArgs e)
        {
            this.uiPagination1.ActivePage = 1;
        }

        /// <summary>
        /// 数据库对象
        /// </summary>
        static SqlSugarDapper _SqlSugarDapper = SqlSugarDapper.GetDbContext();

        /// <summary>
        /// 成绩绑定
        /// </summary>
        private void TaskTableBind()
        {
            //获取当前页面的index
            int index = this.uiPagination1.ActivePage - 1;
            int pageIndex = this.uiPagination1.ActivePage;
            int size = this.uiPagination1.PageSize;
            int begin = (index * size) + 1;
            int end = (index + 1) * size;
            int count = 0;
            this.dgvScoreList.DataSource = "SELECT CallStation,isSupply,MaterialType,SupplyNum ,CASE CallStation WHEN '3001' THEN 'D1'WHEN '3002' THEN 'D2' WHEN '3003' THEN 'D3' WHEN '3004' THEN 'D4' WHEN '3005' THEN 'D5' WHEN '3006' THEN 'C1'WHEN '3007' THEN 'C2' WHEN '3008' THEN 'C3' WHEN '3009' THEN 'C4' WHEN '3010' THEN 'C5' ELSE 'null' END FROM WCS_CallMaterial WHERE 1=1".QueryStrCount(out count);
        }

        /// <summary>
        /// 刷新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnFind_Click(object sender, EventArgs e)
        {
            TaskTableBind();
        }

        /// <summary>
        /// 页面改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="pagingSource"></param>
        /// <param name="pageIndex"></param>
        /// <param name="count"></param>
        private void uiPagination1_PageChanged(object sender, object pagingSource, int pageIndex, int count)
        {
            TaskTableBind();
        }

        /// <summary>
        /// 叫料
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiButton1_Click(object sender, EventArgs e)
        {
            string callStation = "";
            string mes = "";

            if (uiComboBox1.Text == "" || MaterialTypeComboBox.Text == "")
            {
                MessageBox.Show($"站台和物料类型不能为空");

                return;
            }

            DialogResult res = MessageBox.Show($"确定要呼叫{MaterialTypeComboBox.Text}的铸造任务？", "叫料提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (res == DialogResult.OK)
            {
                var matericalcode = _SqlSugarDapper.DB.Queryable<PalletToMaterial>()
                 .Where(w => w.MaterialType == MaterialTypeComboBox.Text)
                 .First();

                var count = _SqlSugarDapper.DB.Queryable<WarehouseInfo>()
                    .Where(w => w.barCode.Contains($"{matericalcode.PalletCode}"))
                    .ToList().Count();

                if (count < 2 || count == 0)
                {
                    MessageBox.Show($"{MaterialTypeComboBox.Text}可用砂芯数量不足");

                    return;
                }

                var info = GetWarehouseByMaterialTypeOut(1, MaterialTypeComboBox.Text, ref mes);
                if (info == null)
                {
                    MessageBox.Show($"{MaterialTypeComboBox.Text}在库时间未满2小时");
                    return;
                }
                switch (uiComboBox1.Text)
                {
                    case "D1":
                        callStation = "3001";
                        break;
                    case "D2":
                        callStation = "3002";
                        break;
                    case "D3":
                        callStation = "3003";
                        break;
                    case "D4":
                        callStation = "3004";
                        break;
                    case "D5":
                        callStation = "3005";
                        break;
                    case "C1":
                        callStation = "3006";
                        break;
                    case "C2":
                        callStation = "3007";
                        break;
                    case "C3":
                        callStation = "3008";
                        break;
                    case "C4":
                        callStation = "3009";
                        break;
                    case "C5":
                        callStation = "3010";
                        break;
                    default:
                        break;
                }

                Entity.CallMaterial callMaterial1 = new Entity.CallMaterial()
                {
                    CallStation = callStation,
                    isSupply = 0,
                    SupplyNum = 2,
                    MaterialType = MaterialTypeComboBox.Text,
                };

                _SqlSugarDapper.DB.Insertable(callMaterial1)
                    .ExecuteCommand();

                MessageBox.Show($"{MaterialTypeComboBox.Text}叫料成功");

                TaskTableBind();
            }
            else
            {
                return;
            }
        }

        /// <summary>
        /// 站台
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiComboBox1_DropDown(object sender, EventArgs e)
        {
            uiComboBox1.Items.Clear();
            foreach (var item in _station)
            {
                uiComboBox1.Items.Add(item.Key);
            }
        }

        /// <summary>
        /// 物料
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MaterialTypeComboBox_DropDown(object sender, EventArgs e)
        {
            var list = _SqlSugarDapper.DB.Queryable<Entity.PalletToMaterial>()
              .ToList()
              .Where(w => !w.MaterialType.Contains("物料"))
              .OrderBy(w => w.MaterialType)
              .GroupBy(w => w.MaterialType)
              .ToList();

            MaterialTypeComboBox.Items.Clear();
            foreach (var item in list)
            {
                MaterialTypeComboBox.Items.Add(item.Key);
            }
        }

        /// <summary>
        /// 根据物料类型查找所在仓库
        /// </summary>
        /// <param name="material"></param>
        /// <returns></returns>
        public static List<WarehouseInfo> GetWarehouseByMaterialTypeOut(int isFullMaterial, string materialType, ref string mes)
        {
            List<WarehouseInfo> strings = new List<WarehouseInfo>();

            var warehouseListGroup = _SqlSugarDapper.DB.SqlQueryable<WarehouseInfo>($@"SELECT * FROM WCS_WarehouseInfo WHERE ID IN (  SELECT   ID  FROM   WCS_Warehouse
                        WHERE   IsFullMaterial = {isFullMaterial}  AND MaterialType = '{materialType}' )
                     ORDER BY [index]").ToList().GroupBy(g => g.ID).ToList();

            foreach (var warehouses in warehouseListGroup)
            {
                var Warehouse = _SqlSugarDapper.DB.Queryable<Warehouse>().Where(w => w.ID == warehouses.Key).First();

                var warehouseInfos = _SqlSugarDapper.DB.SqlQueryable<WarehouseInfo>("SELECT *,DATEDIFF(hh, CreateTime,GETDATE()) as dataIff from WCS_WarehouseInfo").Where(w => w.ID == Warehouse.ID).OrderBy(o => o.index).ToList();

                foreach (var warehouseInfo in warehouseInfos)
                {
                    if (warehouseInfo.dataIff < 2 || warehouseInfo.dataIff > 168)
                    {
                        continue;
                    }
                    strings.Add(warehouseInfo);
                    //判断PLC第二个有没有货
                    if (strings.Count >= 2)
                    {
                        return strings;
                    }
                }
            }
            return null;
        }
    }
}
